package com.aner.test.security.service;


import com.aner.test.cache.DataCache;
import com.aner.test.security.LoginUser;
import com.aner.tester.utils.text.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * token validation
 *
 * @author aner
 * @version 1.0
 * @date 2020/7/6 15:51
 */
@Component
public class TokenService
{
    /**
     * custom token identification
     */
    @Value("${token.header}")
    private String header;

    /**
     * token secret
     */
    @Value("${token.secret}")
    private String secret;

    private static final String LOGIN_TOKEN_KEY = "login_token_key";

    public static final String TOKEN = "token";

    @Autowired
    DataCache dataCache;

    /**
     * get login user info
     * 
     * @return
     */
    public LoginUser getLoginUser(HttpServletRequest request)
    {
        // get token from the request
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            Claims claims = parseToken(token);
            String uuid = (String) claims.get(LOGIN_TOKEN_KEY);
            String userKey = getTokenKey(uuid);
            LoginUser user = dataCache.getLoginUser(userKey);
            return user;
        }
        return null;
    }


    /**
     * create token with login user info
     * 
     * @param loginUser
     * @return
     */
    public String createToken(LoginUser loginUser)
    {
        String token = UUID.randomUUID().toString();;
        loginUser.setToken(token);
        Map<String, Object> claims = new HashMap<>();
        claims.put(LOGIN_TOKEN_KEY, token);
        String userKey = getTokenKey(loginUser.getToken());
        dataCache.putLoginUser(userKey, loginUser);
        return createToken(claims);
    }
    
    /**
     * create token with claims
     *
     * @param claims
     * @return
     */
    private String createToken(Map<String, Object> claims)
    {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

    /**
     * get claim from token
     *
     * @param token
     * @return
     */
    private Claims parseToken(String token)
    {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * get token from request
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(header);
        return token;
    }

    /**
     * get token key
     *
     * @param uuid
     * @return
     */
    private String getTokenKey(String uuid)
    {
        return LOGIN_TOKEN_KEY + uuid;
    }

}
